import router, { constantRoutes, developRoute } from '@/router'
import Layout from '@/layout'

function importComponent(org) {
  for (let item of org) {
    if (item.component != '') {
      item.component = item.component == 'Layout' ? Layout : require(`@/views/${item.component}.vue`).default
    } else {
      item.component = null
    }
    if (item.children) importComponent(item.children)
  }
}

const state = {
  routes: [],
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    let _routes = constantRoutes.concat(routes)
    router.addRoutes(routes)
    if (process.env.NODE_ENV === 'development') {
      _routes = _routes.concat(developRoute)
      router.addRoutes(developRoute)
    }
    state.routes = _routes
  },
}

const actions = {
  async addRouteOfRule({ commit }, data) {
    // console.log('####addRouteOfRule1', data)

    importComponent(data)
    // console.log('####addRouteOfRule2', data)
    data.push({ path: '*', redirect: '/404', hidden: true })
    commit('SET_ROUTES', data)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
